/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.university.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.university.entity.University;
import com.thinkgem.jeesite.modules.university.entity.UniversityOrg;
import com.thinkgem.jeesite.modules.university.service.UniversityOrgService;
import com.thinkgem.jeesite.modules.university.utils.UniversityOrgUtils;
import com.thinkgem.jeesite.modules.university.utils.UniversityUtils;

/**
 * 组织机构Controller
 * @author 朱俊吉
 * @version 2017-12-16
 */
@Controller
@RequestMapping(value = "${adminPath}/university/universityOrg")
public class UniversityOrgController extends BaseController {

	@Autowired
	private UniversityOrgService universityOrgService;
	
	@ModelAttribute
	public UniversityOrg get(@RequestParam(required=false) String id) {
		UniversityOrg entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = universityOrgService.get(id);
		}
		if (entity == null){
			entity = new UniversityOrg();
		}
		return entity;
	}
	@RequiresPermissions("university:universityOrg:view")
	@RequestMapping(value = {""})
	public String index(UniversityOrg universityOrg, Model model) {
		return "modules/university/universityOrgIndex";
	}
	
	@RequiresPermissions("university:universityOrg:view")
	@RequestMapping(value = {"list"})
	public String list(UniversityOrg universityOrg, HttpServletRequest request, HttpServletResponse response, Model model) {
		//查询点击节点下的所有子节点
		model.addAttribute("list", universityOrgService.findByCodeLike(universityOrg));
		return "modules/university/universityOrgList";
	}

	@RequiresPermissions("university:universityOrg:view")
	@RequestMapping(value = "form")
	public String form(UniversityOrg universityOrg, Model model) {
		// 自动获取排序号和编号
		UniversityOrgUtils.setSortAndCode(universityOrg);
		
		model.addAttribute("universityOrg", universityOrg);
		
		return "modules/university/universityOrgForm";
	}

	@RequiresPermissions("university:universityOrg:edit")
	@RequestMapping(value = "save")
	public String save(UniversityOrg universityOrg, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, universityOrg)){
			return form(universityOrg, model);
		}
		universityOrgService.save(universityOrg);
		//没有父节点说明添加的是顶级节点，设置其父节点为默认等级节点
		if(universityOrg.getParent() == null || UniversityOrgUtils.TOP_NODE_ID.equals(universityOrg.getParent().getId())){
			universityOrg.setParent(UniversityOrgUtils.TOP_ORG_NODE);
		}
		addMessage(redirectAttributes, "保存组织机构成功");
		return "redirect:"+Global.getAdminPath()+"/university/universityOrg/list?id="+universityOrg.getParent().getId()+"&code="+universityOrg.getParent().getCode();
	}
	
	@RequiresPermissions("university:universityOrg:edit")
	@RequestMapping(value = "delete")
	public String delete(UniversityOrg universityOrg, RedirectAttributes redirectAttributes) {
		universityOrgService.delete(universityOrg);
		addMessage(redirectAttributes, "删除组织机构成功");
		return "redirect:"+Global.getAdminPath()+"/university/universityOrg/?repage";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<UniversityOrg> list = universityOrgService.findAllList();
		for (int i=0; i<list.size(); i++){
			UniversityOrg e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("code", e.getCode());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
	/**
	 * 导出用户数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("university:universityOrg:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(UniversityOrg universityOrg, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "学校组织机构数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            List<UniversityOrg> list = universityOrgService.findByParentIdsLike(universityOrg);
            for (UniversityOrg org : list) {
            	//parentIds不为空且不是最"0,"
        		if (StringUtils.isNotBlank(org.getParentIds()) && !"0,".equals(org.getParentIds())){
        			
        			String[] parentIds = org.getParentIds().toString().split(",");
        			StringBuilder sb = new StringBuilder();
        			for (String parentId : parentIds) {
        				if(!"0".equals(parentId)){
        					UniversityOrg o = universityOrgService.get(parentId);
        					sb.append(o.getName()+"-");
        				}
        			}
        			org.setParentIds(sb.toString().substring(0, sb.length() - 1));
        		}else{
        			org.setParentIds("");
        		}
			}
    		new ExportExcel("学校组织机构数据", UniversityOrg.class)
    			.setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出学校组织机构失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/university/universityOrg/list?repage";
    }
	/**
	 * 导入学校组织机构数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("university:universityOrg:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/university/universityOrg/list?repage";
		}
		try {
			//记录成功条数
			int successNum = 0;
			//记录失败条数
			int failureNum = 0;
			//导入信息记录
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<UniversityOrg> list = ei.getDataList(UniversityOrg.class);
			for (UniversityOrg org : list){
				//名称为空不能导入
				if(StringUtils.isBlank(org.getName())){
					continue ;
				}
				String parentIds = org.getParentIds();
				//Excel有上级机构时，查询上级机构是否存在，不存在补齐上级机构
				if(StringUtils.isNotBlank(parentIds)){
					//强制要求导入数据父节点以   （北京大学-理学部）格式传入，节点之间用"-"分隔
					String[] parents = org.getParentIds().split("-");
					//父节点集合
					List<UniversityOrg> higherList = Lists.newArrayList();
					for (int i = 0; i < parents.length; i++) {
						UniversityOrg o = null;
						if(i == 0){
							//第一级节点为大学通过名称查询是否存在
							UniversityOrg higherOrg = new UniversityOrg();
							higherOrg.setParent(UniversityOrgUtils.TOP_ORG_NODE);
							//等同于  select * fromt wd_university_organization where parent_id = '0'
							List<UniversityOrg> childList = universityOrgService.findList(higherOrg);
							if(childList != null && childList.size() > 0){
								for (UniversityOrg child : childList) {
									if(StringUtils.trimToEmpty(parents[i]).equals(child.getName())){
										o = child;
									}
								}
							}
						}else{
							//非第一级时通过查询上级子节点
							UniversityOrg higherOrg = new UniversityOrg();
							higherOrg.setParent(higherList.get(i-1));
							List<UniversityOrg> childList = universityOrgService.findList(higherOrg);
							if(childList != null && childList.size() > 0){
								for (UniversityOrg child : childList) {
									if(StringUtils.trimToEmpty(parents[i]).equals(child.getName())){
										o = child;
									}
								}
							}
						}
						//补全不存在的节点
						if(o == null){
							o = new UniversityOrg();
							if(i > 0){
								o.setParent(higherList.get(i-1));
							}else{
								o.setParent(UniversityOrgUtils.TOP_ORG_NODE);
							}
							o.setName(parents[i]);
							//设置Sort和Code
							UniversityOrgUtils.setSortAndCode(o);
							//设置类型和等级
							o.setType(i+"");
							o.setGrade(i+"");
							UniversityOrgUtils.setSortAndCode(o);
							universityOrgService.save(o);
						}
						higherList.add(o);
					}

					//得到父节点
					UniversityOrg parent = higherList.get(higherList.size()-1);
					//设置父节点
					org.setParent(parent);
					// 设置新的父节点串
					org.setParentIds(parent.getParent().getParentIds()+parent.getParent().getId()+",");
					
					try{
						if(UniversityOrgUtils.exist(org)){
							//存在此节点不保存
							failureMsg.append("<br/>组织机构 "+org.getName()+" 已存在; ");
							failureNum++;
						}else{
							//不存在此节点保存
							BeanValidators.validateWithException(validator, org);
							UniversityOrgUtils.setSortAndCode(org);
							universityOrgService.save(org);
							successNum++;
						}
					}catch(ConstraintViolationException ex){
						failureMsg.append("<br/>组织机构 "+org.getName()+" 导入失败：");
						List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
						for (String message : messageList){
							failureMsg.append(message+"; ");
							failureNum++;
						}
					}catch (Exception ex) {
						failureMsg.append("<br/>组织机构 "+org.getName()+" 导入失败："+ex.getMessage());
					}
				}
				
				//没有上级机构时
				if(StringUtils.isBlank(parentIds)){
					if(UniversityOrgUtils.exist(org)){
						//存在此节点不保存
						failureMsg.append("<br/>组织机构 "+org.getName()+" 已存在; ");
						failureNum++;
					}else{
						//节点不存在 保存数据
						UniversityOrgUtils.setSortAndCode(org);
						org.setType("1");
						org.setGrade("1");
						universityOrgService.save(org);
						successNum++;
					}
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条组织机构，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条组织机构"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入组织机构失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/university/universityOrg/list?repage";
    }
	
	/**
	 * 下载导入学校组织机构数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("university:universityOrg:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "学校组织机构数据模板.xlsx";
    		List<UniversityOrg> list = Lists.newArrayList();
    		UniversityOrg universityOrg = new UniversityOrg();
    		universityOrg.setName("物理学院");
    		universityOrg.setType("3");
    		universityOrg.setGrade("3");
    		universityOrg.setParentIds("北京大学-理学部");
    		list.add(universityOrg);
    		new ExportExcel("学校组织机构数据", UniversityOrg.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/university/universityOrg/list?repage";
    }
}